from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyModelFrom, PrettyEditModelFrom


def pretty_list(request):
    """靓号列表"""
    # <QuerySet [<PrettyNum: PrettyNum object (9)>]>

    # int::
    # id__gt    >
    # id__gte   >=
    # id__lt    <
    # id__lte   <=

    # char::
    # mobile__startswith='199'  以199开头
    # mobile__endswith='199'    以199结尾
    # mobile__contains='199'    包含199的

    """q1 = models.PrettyNum.objects.filter(mobile='17747121704', id=9)
    print(q1)

    # <QuerySet [<PrettyNum: PrettyNum object (9)>]>
    data_dict = {"mobile": '17747121704', "id": 9}
    q2 = models.PrettyNum.objects.filter(**data_dict)
    print(q2)"""

    # q有值则为q, 无则为空
    search_data = request.GET.get('q', '')
    print(search_data)
    queryset = models.PrettyNum.objects.filter(mobile__contains=search_data).order_by('-level')

    page_obj = Pagination(request, queryset)

    context = {
        'pre_set': page_obj.page_queryset,
        # 分完页的数据
        'search_data': search_data,
        # 页码
        'page_str': page_obj.html()
    }

    return render(request, 'pretty_list.html', context)


def pretty_add(request):
    """新建靓号"""
    if request.method == 'GET':
        form = PrettyModelFrom()
        return render(request, 'pretty_add.html', {'form': form})
    # 数据校验
    form = PrettyModelFrom(data=request.POST)
    if form.is_valid():
        # 格式校验

        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_add.html', {'form': form})


def pretty_edit(request, nid):
    """编辑靓号"""
    row_obj = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyEditModelFrom(instance=row_obj)
        return render(request, 'pretty_edit.html', {'form': form})

    form = PrettyEditModelFrom(data=request.POST, instance=row_obj)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据; 如果想要再用户输入以外在增加值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {'form': form})


def pretty_delete(request, nid):
    """删除靓号"""
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')
